package com.zhaojonhy.zhaopangwb.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.File;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * Created by Administrator on 2016/11/4.
 */

public class GifImageUtils {

    private final static String TAG = GifImageUtils.class.getSimpleName() ;
    private static Activity context ;

    public GifImageUtils(Activity context) {
        this.context = context ;
    }

    public static void displayImage(String url, final GifImageView gifView) {
        File saveImgPath = getImgDir(context) ;
        File saveFile = new File(saveImgPath,"gif") ;
        HttpUtils http = new HttpUtils();
        // 下载图片
        http.download(url, saveFile.getAbsolutePath(), new RequestCallBack<File>() {
            public void onSuccess(ResponseInfo<File> responseInfo) {
                try {
                    GifDrawable gifFrom = new GifDrawable(responseInfo.result.getAbsolutePath());
                    gifView.setImageDrawable(gifFrom);
                } catch (Exception e) {
                    Log.d(TAG, e.getMessage());
                }
            }

            public void onFailure(HttpException error, String msg) {
                Log.d(TAG, "onFailure========" + msg);
            }
        });
    }

    public static File getFilesDir(Context context, String tag){
        if(isSdCardExist() == true){
            return context.getExternalFilesDir(tag);
        }
        else{
            return context.getFilesDir();
        }
    }
    public static File getImgDir(Context context) {
        File file = getFilesDir(context,"images") ;
        return file;
    }

    public static boolean isSdCardExist() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }
}
